package parser;

import java.util.List;

public class Root extends Node {
	private Node result;
	private boolean isTopLevel;

	public Root(String newType, boolean newTopLevel) {
		super(newType);
		result = null;
		isTopLevel = newTopLevel;
	}

	public Root(String newType, String newConstraint, boolean newTopLevel) {
		super(newType, newConstraint);
		result = null;
		isTopLevel = newTopLevel;
	}

	public boolean isTopLevel() {
		return isTopLevel;
	}

	public void setTopLevel(boolean isTopLevel) {
		this.isTopLevel = isTopLevel;
	}

	public Node getResult() {
		return result;
	}

	public void setResult(Node result) {
		this.result = result;
	}

	public String getQuery() {
		String query = "";
		if (isTopLevel)
			query += "/";
		else
			query += "//";

		return query + getSubQuery(this);
	}

	private String getSubQuery(Node node) {
		String type = "";
		String path = "";
		String attribute = "";

		if (node.isAttribute) {
			type = "@" + node.type;
			if (node.getChild().isEmpty())
				return type;
			else {
				String value = node.getChild().get(0).getType();
				if(value.startsWith(Constant.PREFIX))
					value = value.substring(Constant.PREFIX.length());
				return type + "=" + value;
			}
		} else {
			if (!node.getChild().isEmpty()) {
				List<Node> children = node.getChild();
				for (Node child : children) {
					String temp = getSubQuery(child);
					if (child.isInPath)
						path += "/" + temp;
					else {
						if (attribute.equals(""))
							attribute += temp;
						else
							attribute += " and " + temp;
					}
				}
			}

			if (!node.getDecendant().isEmpty()) {
				List<Node> descendants = node.getDecendant();
				for (Node descendant : descendants) {
					String temp = getSubQuery(descendant);
					if (descendant.isInPath)
						path += "//" + temp;
					else {
						if (attribute.equals(""))
							attribute += "//" + temp;
						else
							attribute += " and //" + temp;
					}
				}
			}
		}

		type = node.isAttribute ? "@" + node.type : node.type;

		if (attribute.equals(""))
			return type + path;
		else
			return type + "[" + attribute + "]" + path;
	}
}